package com._520it.crm.web.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com._520it.crm.domain.Employee;
import com._520it.crm.page.PageResult;
import com._520it.crm.query.EmployeeQuery;
import com._520it.crm.service.IEmployeeService;
import com._520it.crm.util.JsonResult;
import com._520it.crm.util.UserContext;

@Controller
public class EmployeeController {
	
	@Autowired
	private IEmployeeService service;
	
	@RequestMapping("/employee_save")
	@ResponseBody
	public JsonResult save(Employee employee){
		JsonResult result = new JsonResult();
		try{
			service.insert(employee);
			result.setSuccess(true);
			result.setMsg("保存成功！");
		}catch (Exception e) {
			//记录日志
			result.setSuccess(false);
			result.setMsg("保存失败！");
		}
		return result;
	}
	
	@RequestMapping("/employee_update")
	@ResponseBody
	public JsonResult update(Employee employee){
		JsonResult result = new JsonResult();
		try{
			service.updateByPrimaryKey(employee);
			result.setSuccess(true);
			result.setMsg("更新成功！");
		}catch (Exception e) {
			//记录日志
			result.setSuccess(false);
			result.setMsg("更新失败！");
		}
		return result;
	}
	
	
	@RequestMapping("/employee_list")
	@ResponseBody
	public PageResult list(EmployeeQuery qo){
		return service.queryPageResult(qo);
	}
	
	@RequestMapping("/employee")
	public String index(){
		return "employee";
	}
	
	
	@RequestMapping("/login")
	@ResponseBody
	public JsonResult login(String username,String password,HttpSession session){
		//去数据库里面查询是否有该账户和密码
		Employee employee = service.getEmployeeByLogin(username, password);
		JsonResult result = new JsonResult();
		if(employee!=null){
			//放入session中
			session.setAttribute(UserContext.USERINSESSION, employee);
			result.setSuccess(true);
		}else{
			result.setSuccess(false);
			result.setMsg("登录失败，请检查你的输入的密码！");
		}
		return result;
	} 
	
	@RequestMapping("/employee_updateState")
	@ResponseBody
	public JsonResult updateStatee(Long id){
		JsonResult result = new JsonResult();
		try{
			service.updateState(id);
			result.setSuccess(true);
			result.setMsg("保存成功！");
		}catch (Exception e) {
			//记录日志
			result.setSuccess(false);
			result.setMsg("保存失败！");
		}
		return result;
	}
	
}
